<?php

class SiteController extends Controller
{
	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// By default we will redirect to the store main page
		$dsn_url = 'http://casabento.com/shop/';
		if (array_key_exists('products_id', $_GET))
		{
			// checks to see if old product id maps to anything
			$mapping = Mapping::model()->findByAttributes(array('old_product_id' => $_GET['products_id']));
			if (!is_null($mapping)) {
				$dsn_url = vsprintf('http://casabento.com/shop/product.php?id_product=%d', $mapping->new_product_id);
			}
		}
		elseif (array_key_exists('cPath', $_GET))
		{
			$mapping = Mapping::model()->findByAttributes(array('old_category_id' => $_GET['cPath']));
			if (!is_null($mapping)) {
				$dsn_url = vsprintf('http://casabento.com/shop/category.php?id_category=%d', $mapping->new_category_id);
			}
		}
		header("HTTP/1.1 301 Moved Permanently");
		header(vsprintf("Location: %s", $dsn_url));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
}
